package com.jokerku.mini.schedule.event;

import com.jokerku.mini.schedule.common.Constants;
import com.jokerku.mini.schedule.service.HeartbeatService;
import com.jokerku.mini.schedule.sharding.ShardingService;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Author: guzq
 * @CreateTime: 2023/06/18 16:08
 * @Description: ip节点事件
 * @Version: 1.0
 */
public class ServerNodeEventListener implements ScheduleEventListener<PathChildrenCacheEvent> {

    private static final Logger logger = LoggerFactory.getLogger(ServerNodeEventListener.class);

    @Override
    public void consumeEvent(PathChildrenCacheEvent childrenCacheEvent) {
        ChildData data = childrenCacheEvent.getData();
        String path = data.getPath();

        switch (childrenCacheEvent.getType()) {
            case CHILD_ADDED:
                // 子节点被创建
                logger.info("Child node created:{}", path);
                ShardingService.getInstance().setReShardingFlag();
                ShardingService.getInstance().shardingIfNecessary();
                break;
            case CHILD_UPDATED:
                // 子节点被更新
                break;
            case CHILD_REMOVED:
                // 子节点被删除
                logger.info("Child node deleted:{}", path);
                String ip = path.substring(path.lastIndexOf(Constants.Global.LINE) + 1);
                logger.info("Offline ip:{}", ip);
                ShardingService.getInstance().setReShardingFlag();
                ShardingService.getInstance().shardingIfNecessary();
                break;
            default:
                break;
        }
    }
}
